<template>
  <div id="app">
    <div class="head">
      <div class="head-title">
        <p>系统日志</p>
      </div>
    </div>
    <div class="main">
      <div class="block">
        <span class="demonstration">请选择时间 </span>
        <el-date-picker
          @change="current"
          v-model="searchTime"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
        >
        </el-date-picker>
      </div>

      <div class="block">
        <span class="demonstration">选择菜单 </span>
        <el-cascader
          v-model="value"
          :options="options"
          @change="handleChange"
          clearable
        ></el-cascader>
      </div>
      <div class="block" style="display: flex">
        <span
          style="display: flex;  align-items: center;width: 50px;"
          >搜索</span
        >
        <el-input
          placeholder="请输入内容"
          v-model="logSearchKeyword"
          clearable
          @change="handleSearch"
        >
        </el-input>
      </div>
    </div>
    <div class="under">
      <div class="dataTest">
        <el-table
          :data="
            tableALLDataList.slice(
              (currentPage - 1) * pageSize,
              currentPage * pageSize
            )
          "
          style="width: 100%"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column type="index" width="50" label="序号">
          </el-table-column
          ><el-table-column
            prop="time"
            label="时间"
            sortable
            width="300
            "
          ></el-table-column>
          <el-table-column prop="type" label="类型" sortable width="200">
            <template slot-scope="{ row }">
              <!-- <span>{{ LogMainEnums[Number(row.type)] }}</span> -->
              <span>{{ row.type }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="childtype" label="子类型" sortable width="200">
          </el-table-column>
          <el-table-column prop="contentstr" label="操作内容" sortable>
          </el-table-column>
        </el-table>
        <div class="block">
          <span class="demonstration"> </span>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[100, 200, 300, 400]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableALLDataList.length"
          >
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script >
// import { filter } from 'vue/types/umd';
// import { options1 } from "../../router/options1";
// import Vue from ;
// new Vue().$mount('app')\

import { LogMainEnum, LogChildEnum } from "./enum";
export default {
  data() {
    return {
      logSearchKeyword: "", //日志搜索关键字 模糊搜索
      type: "",
      currentPage: 1,
      pageSize: 100,
      all: [],
      obj: {},
      tableALLDataList: [], //处理过后的表格所有数组
      tableALLDataListCopy: [], //处理过后的表格所有数组copy(搜索用)
      tableInfo: [], //处理过后的表格数组
      dataSet: [],
      tableData: [],
      sysDataAllLogUrl: [],
      startTime: "", //起始日期
      endTime: "", //结束日期
      todayLogs: [],
      lastWeekLogs: [],
      last30DaysLogs: [],
      devices: {},
      value: null,
      options: [
        {
          id: 1,
          value: "系统日志",
          label: "系统日志",
          children: [
            {
              value: "系统初始化",
              label: "系统初始化",
            },
            {
              value: "参数修改",
              label: "参数修改",
            },
            {
              value: "系统退出",
              label: "系统退出",
            },
            {
              value: "用户登陆",
              label: "用户登陆",
            },
            {
              value: "其他",
              label: "其他",
            },
          ],
        },
        {
          id: 2,
          value: "操作日志",
          label: "操作日志",
          children: [
            {
              value: "主机寻呼",
              label: "主机寻呼",
            },
            {
              value: "主机告警",
              label: "主机告警",
            },
            {
              value: "消防告警",
              label: "消防告警",
            },
            {
              value: "设备间寻呼",
              label: "设备间寻呼",
            },
            {
              value: "设备间对讲",
              label: "设备间对讲",
            },
            {
              value: "播放钟声",
              label: "播放钟声",
            },
            {
              value: "定时节目",
              label: "定时节目",
            },
            {
              value: "播放节目",
              label: "播放节目",
            },
            {
              value: "点播节目",
              label: "点播节目",
            },
            {
              value: "停止",
              label: "停止",
            },
            {
              value: "其他",
              label: "其他",
            },
          ],
        },
        {
          id: 3,
          value: "设备日志",
          label: "设备日志",
          children: [
            {
              value: "主机寻呼",
              label: "主机寻呼",
            },
            {
              value: "主机告警",
              label: "主机告警",
            },
            {
              value: "消防告警",
              label: "消防告警",
            },
            {
              value: "设备间寻呼",
              label: "设备间寻呼",
            },
            {
              value: "设备间对讲",
              label: "设备间对讲",
            },
            {
              value: "播放钟声",
              label: "播放钟声",
            },
            {
              value: "定时节目",
              label: "定时节目",
            },
            {
              value: "播放节目",
              label: "播放节目",
            },
            {
              value: "点播节目",
              label: "点播节目",
            },
            {
              value: "其他",
              label: "其他",
            },
            {
              value: "所有",
              label: "所有",
            },
          ],
        },
      ],

      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date(new Date().toLocaleDateString()).getTime());
              picker.$emit("pick", [start, end]);
            },
          },
        ],
        disabledDate(time) {
          let limit = Date.now() - 3600 * 1000 * 24 * 30;
          return time.getTime() > Date.now() || time.getTime() < limit; // 设置禁止选今天以后的日子
        },
      },

      list: ["diyi", "dier"],
      value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
      searchTime: "",
      value2: "",
      //   pickerOptions: options1,
      date: "",
      date2: "",
    };
  },

  mounted() {
    // this.fetchDevices();
    // this.fetchLogs();
    // this.initData();
    // this.LogMainEnums=LogMainEnum
    // console.log('111',LogMainEnum)
  },
  created() {
    console.log();
  },
  watch: {},
  computed: {
    dtableALLDataList() {
      if (!this.options) {
        return this.item;
      } else {
        return this.item.filter((item) => item.value === this.selectType);
      }
    },
  },
  methods: {
    /**
     * @use 菜单搜索
     */
    handleChange(e) {
      if (e.length == 0) {
        this.tableALLDataList = this.tableALLDataListCopy;
        return;
      }
      this.tableALLDataList = this.tableALLDataListCopy.filter((item) => {
        return item.type == e[0] && item.childtype == e[1];
      });
    },
    /**
     * @use 搜索查找日志
     */

    handleSizeChange(size) {
      this.pageSize = size;
      console.log(`每页 ${size} 条`);
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      console.log(`当前页: ${currentPage}`);
    },
    current() {
      // console.log("当前你", this.searchTime);

      // console.log("before1", this.searchTime[0]);
      // console.log("before2", this.searchTime[1]);

      this.startTime = new Date(Date.parse(this.searchTime[0]));
      this.endTime = new Date(Date.parse(this.searchTime[1]));

      let startDate = this.startTime;
      let endDate = this.endTime;
      // console.log("开始", this.startTime);
      // console.log("结束", this.endTime);
      // const year=endDate.getFullYear()
      // const month=end.getMonth()+1
      // const day=endTime.getDate()
      this.fetchLogs(startDate, endDate);
    },

    async fetchLogs(startDate, endDate) {
      this.sysDataAllLogUrl = [];
      this.$axios
        .get("/api/getthedirfileinfo?path=log/sys/")
        .then((response) => {
          const allLogs = response.data;
          // console.log("allLogs", allLogs);
          const logTime = Object.keys(allLogs);
          console.log("111", logTime);
          // console.log("logTime", logTime);
          for (let key in allLogs) {
            if (Object.hasOwnProperty.call(allLogs, key)) {
              let logDateStr = allLogs[key].name.substring(
                0,
                allLogs[key].name.indexOf("_")
              );
              // console.log( '1',logDateStr)
              let logDate = new Date(Date.parse(logDateStr));
              // console.log("shijiancuo",logDate)
              // console.log("startTime",startDate)
              // console.log("endTime",endDate)
              if (
                typeof startDate !== "undefined" &&
                typeof endDate !== "undefined"
              ) {
                if (startDate <= logDate && endDate >= logDate) {
                  // console.log( '22',logTime)
                  this.sysDataAllLogUrl.push("/" + key);
                }
              } else {
                this.sysDataAllLogUrl.push("/" + key);
              }
            }
          }

          // console.log("5555", this.sysDataAllLogUrl);
          const all = [];

          this.sysDataAllLogUrl.forEach((ele) => {
            // console.log("555", ele);
            this.$axios.get(`http://localhost/${ele}`).then((res) => {
              let result = res.data;
              // console.log("res", result);
              const index = result.lastIndexOf(",");
              // console.log("index",index)

              var onefile = result.substring(0, index);
              onefile = "[" + onefile + "]";
              // console.log("onefile", onefile);
              // var reg = /(\d+),(\d+),'([\s\S]*)'/;
              var dataarr = JSON.parse(onefile);
              // console.log("datataarr", dataarr);

              const arr = [];

              dataarr.forEach((element) => {
                const obj = new Object();
                // var online=[];
                // console.log("element", element);

                // 正则表达分割content信息
                var reg = /(\d+),(\d+),'([\s\S]*)'/;
                reg.exec(element.content);
                // console.log("dataStamp",dataStamp)
                var type = RegExp.$1;
                var childtype = RegExp.$2;
                var contentstr = RegExp.$3;

                obj.type = LogMainEnum[Number(type)];

                obj.childtype = LogChildEnum[Number(childtype)];
                obj.contentstr = contentstr;
                obj.time = element.time;

                // console.log("obj", obj);
                arr.push(obj);
                // console.log("arr",arr)
                // console.log("arr",arr)
                // this.tableInfo.push(this.obj);
                // console.log("arr", this.tableInfo);

                // this.tableALLDataList.push(...this.tableInfo)
                // console.log("all",this.tableALLDataList);
                // console.log("element.time",element.time)
                // let oneline = [];
                // oneline.push(element.time, type, childtype, contentstr);
                // console.log("oneline", oneline);
                // oneline = oneline.map((item) => {
                //   return {
                //     time: item[0],
                //     type: item[1],
                //     childtype: item[2],
                //     contentstr: item[3],
                //   };
                // });

                // console.log('2222',oneline)

                // const arr=[]
                // arr.map(()=>{
                //   return {

                //     type:type,
                //     childtype:childtype
                //   }

                // })

                // this.Reg.exec(element.content)
                // console.log
                // online.push(this.dataSet.length+2,element.time.item,type,childtype,contentstr)
                // this.dataSet.push(online)
              });
              // console.log("123", arr);
              // this.tableALLDataList.push(...arr)
              all.push(...arr);
              // this.tableALLDataList=[...this.tableALLDataList,...arr]
              // console.log('全部',all)
              this.tableALLDataList = all;
              this.tableALLDataListCopy = this.tableALLDataList;
              console.log("全部2", this.tableALLDataList);
            });
          });
        })
        .catch((error) => {
          console.error("Error fetching logs:", error);
        });
    },
    handleSearch() {
      console.log(this.logSearchKeyword);
      console.log("当前全部数据", this.tableALLDataList);
      // this.tableALLDataList = this.tableALLDataListCopy.filter((item) => {
      //   return (
      //     item.type.search(this.logSearchKeyword) !== -1 ||
      //     item.childtype.search(this.logSearchKeyword) !== -1 ||
      //     item.contentstr.search(this.logSearchKeyword) !== -1 ||
      //     item.time.search(this.logSearchKeyword) !== -1
      //   );
      // });
      this.tableALLDataList = this.tableALLDataListCopy.filter((item) => {
        // console.log("string", Object.keys(item));
        return Object.values(item).some((value) => {
          // console.log("11", value.toLowerCase());
          return (
            value.toLowerCase().indexOf(this.logSearchKeyword.toLowerCase()) !==
            -1
          );
        });
      });

      // console.log(filterData);
      // this.tableALLDataList = filterData;
      // console.log("tableDAta",this.tableALLDataList);
      // console.log("key",this.logSearchKeyword.toLowerCase())
    },
  },
};
</script>
<style scoped></style>